<?php

if ($category['display'] == 'products') {
	
	$search = new ProductSearch();
	
	if (isset($category['id'])) {
		if (isset($_REQUEST['order']) and in_array($_REQUEST['order'], array('', 'alphabetical', 'popular', 'newest', 'price_high_low', 'price_low_high'))) {
			$_SESSION['shop']['category_order'][$category['id']] = $_REQUEST['order'];
		}
		$category['order'] = isset($_SESSION['shop']['category_order'][$category['id']]) ? $_SESSION['shop']['category_order'][$category['id']] : $category['default_order'];
		$search->category($category['id']);
		$search->order($category['order']);
	}
	
	foreach($filters as $filter) {
		list($k, $v) = explode(':', $filter, 2);
		if ($k == 's') {
			$search->query($v);
		} else {
			$search->filter($k, $v);
		}
	}
	
	if (!isset($_SESSION['shop']['category_show'])) $_SESSION['shop']['category_show'] = isset($env['shop']['category_show']) ? $env['shop']['category_show'] : 20;
	if (isset($_REQUEST['show']) and is_numeric($_REQUEST['show'])) $_SESSION['shop']['category_show'] = $_REQUEST['show'];
	if (isset($_REQUEST['show']) and $_REQUEST['show'] == 'all') {
		$_SESSION['shop']['category_show'] = 'all';
		$_REQUEST['page'] = 1;
	}
	
	$category['pagination'] = array('products' => array());
	$category['pagination']['products']['show']   = $_SESSION['shop']['category_show'] == 'all' ? 999999999 : $_SESSION['shop']['category_show'];
	$category['pagination']['products']['show_all'] = $_SESSION['shop']['category_show'] == 'all';
	$category['pagination']['products']['page']   = (isset($_REQUEST['page']) and is_numeric($_REQUEST['page'])) ? $_REQUEST['page'] : 1;
	$category['pagination']['products']['offset'] = ($category['pagination']['products']['page'] - 1) * $category['pagination']['products']['show'];
	
	$category['products'] = $search->results($category['pagination']['products']['offset'], $category['pagination']['products']['show']);
	
	$category['pagination']['products']['total']  = $search->totalResults();
	$category['pagination']['products']['pages']  = ceil($category['pagination']['products']['total'] / $category['pagination']['products']['show']);
	
	$category['filters'] = $search->filters;
	
}

if ($category['display'] == 'subcategories') {
	$category['subcategories'] = $db->fetchAll("SELECT c.*, COUNT(*) AS product_count FROM shop_categories c LEFT JOIN shop_categories_products cp ON c.id=cp.category_id LEFT JOIN shop_products p ON cp.product_id=p.id WHERE c.parent_id=? AND p.active=1 AND p.deleted=0 GROUP BY c.id HAVING product_count ORDER BY c.sort, c.title", $category['id']);
	foreach($category['subcategories'] as $i => $subcategory) {
		$category['subcategories'][$i]['images'] = shop_get_images('categories', $subcategory['image'] ? $subcategory['image'] : make_path($subcategory['title']));
	}
}

$smarty->assign('category', $category);
$smarty->display('shop/category.tpl.html');
